import requests
from bs4 import BeautifulSoup
import time
if __name__ == '__main__':
    url = 'https://www.shicimingju.com/book/minguoyanyi.html'
    headers = {
        'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    }
    # page_text1 = requests.get(url=url, headers=headers).text
    #上面一行为源代码，输出结果为乱码
    res = requests.get(url=url, headers=headers)
    res.encoding = "utf-8"
    page_text = res.text

    #解析出章节标题和对应url
    #1.实例化bs对象，并加载源码到该对象
    soup = BeautifulSoup(page_text,'lxml')
    soup.originalEncoding
    #2.章节标题和url获取
    li_list = soup.select('.book-mulu > ul > li')
    fp = open('./sanguo.txt','w',encoding='utf-8')
    for li in li_list:
        title = li.a.text
        detail_url = 'https://www.shicimingju.com/'+li.a['href']
        #对详情页发起请求，解析出章节内容
        # detail_page_text = requests.get(url=detail_url,headers=headers).text

        res_detail_page = requests.get(url=detail_url,headers=headers)
        res_detail_page.encoding = "utf-8"
        detail_page_text = res_detail_page.text


        #解析出详情页中相关的章节内容
        detail_soup = BeautifulSoup(detail_page_text,'lxml')
        div_tag = detail_soup.find('div',class_='chapter_content')
        #解析到了章节的内容
        content = div_tag.text

        #持久化存储(with open会被打开多次）
        fp.write(title+':'+content+'\n')
        time.sleep(1)
        print(title,'爬取成功！！！')

    # response = requests.get(url=url,headers=headers)
    # print(response.encoding)